package com.example.lcode.binary;

public class Question222 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int countNodes(TreeNode root) {
        int level = calcLevel(root);
        int leftRange =  1 << (level - 1);
        int rightRange = (1 << level) - 1;
        return calcCount(root, level, leftRange, rightRange);
    }

    private int calcCount(TreeNode root, int level, int leftRange, int rightRange) {
        if (leftRange >= rightRange) {
            return leftRange;
        }
        int mid = (leftRange + rightRange) / 2;
        if (isCorrectCount(root, level, mid)) {
            return calcCount(root, level, mid, rightRange);
        } else {
            return calcCount(root, level, leftRange, mid - 1);
        }
    }

    private boolean isCorrectCount(TreeNode root, int level, int count) {
        // TODO 以进制的形式判断具体数字的路径 二叉树 的左右跟数字 位直等同
        return false;
    }

    private int calcLevel(TreeNode root) {
        int level = 0;
        return doCalcLevel(root, level);
    }

    private int doCalcLevel(TreeNode root, int level){
        if (root == null) {
            return level;
        }
        level ++;
        return doCalcLevel(root.left, level);
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        TreeNode treeNode6 = new TreeNode(6);
        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode2.right = treeNode5;
        treeNode3.left = treeNode6;
        Question222 question222 = new Question222();
        System.out.println(question222.countNodes(treeNode1));
    }

}
